package com.tjb.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tjb.reggie.common.BaseContext;
import com.tjb.reggie.common.TjbException;
import com.tjb.reggie.entity.*;
import com.tjb.reggie.mapper.OrderMapper;
import com.tjb.reggie.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @author tjb
 * @version 1.0
 * @date 2022/8/26 1:09
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {
    @Resource
    private ShoppingCarService shoppingCarService;
    @Resource
    private UserService userService;
    @Resource
    private AddressBookService bookService;
    @Resource
    private OrderDetailService orderDetailService;

    /**
     * 用户下单
     *
     * @param orders
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void submit(Orders orders) {
        //获得当前用户的id
        Long userId = BaseContext.getCurrentUserId();
        //查询当前用户的购物车数据
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> shoppingCarts = shoppingCarService.list(wrapper);
        if (shoppingCarts == null){
            throw new TjbException("购物车空空如也");
        }
        //查询用户的数据
        User user = userService.getById(userId);
        //查询出地址的数据
        Long bookId = orders.getAddressBookId();
        AddressBook addressBook = bookService.getById(bookId);
        if (addressBook == null){
            throw new TjbException("用户地址信息有误,不能下单");
        }
        //订单id
        long id = IdWorker.getId();
        //计算金额
        AtomicInteger amount = new AtomicInteger(0);
        List<OrderDetail> orderDetails = shoppingCarts.stream().map((item) -> {
            //操作订单明细，赋值
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(item, orderDetail);
            orderDetail.setOrderId(id);
            //计算总金额
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());
        //订单赋值
        orders.setId(id);
        orders.setNumber(String.valueOf(id));
        orders.setStatus(2);
        orders.setUserId(userId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        //总金额
        orders.setAmount(new BigDecimal(amount.get()));
        orders.setUserName(user.getName());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName()) +
                          (addressBook.getCityName() == null ? "" : addressBook.getCityName()) +
                          (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName()) +
                          (addressBook.getDetail() == null ? "" : addressBook.getDetail())
        );
        orders.setConsignee(addressBook.getConsignee());

        //想订单表插入数据,一条数据
        this.save(orders);
        //想订单明细表插入数据，多条数据
        orderDetailService.saveBatch(orderDetails);
        //清空购物车数据
        shoppingCarService.remove(wrapper);
    }
}
